class EventDispatcher {
  addEventListener(type, listener) {
    if (this._listeners === undefined) this._listeners = {};
    const listeners = this._listeners;
    if (listeners[type] === undefined) listeners[type] = [];
    if (listeners[type].indexOf(listener) === -1) listeners[type].push(listener);
  }

  hasEventListener(type, listener) {
    if (this._listeners === undefined) return false;
    const listeners = this._listeners;
    return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  }

  removeEventListener(type, listener) {
    if (this._listeners === undefined) return;
    const listeners = this._listeners;
    const listenerArray = listeners[type];
    if (listenerArray !== undefined) {
      const index = listenerArray.indexOf(listener);
      if (index !== -1) listenerArray.splice(index, 1);
    }
  }

  dispatchEvent(type, data) {
    if (this._listeners === undefined) return;
    const myEvent = {};
    const listeners = this._listeners;
    const listenerArray = listeners[type];

    if (listenerArray !== undefined) {
      const arrayCopy = listenerArray.slice(0);
      myEvent.target = this;
      myEvent.detail = data || {};
      arrayCopy.forEach(item => item.call(this, myEvent));
      myEvent.target = null;
    }
  }
}

export default EventDispatcher;
